<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="报销通知" name="notification">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="参保人" prop="insuredName">
            <el-input
              v-model="queryParams.insuredName"
              placeholder="请输入参保人姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="通知状态" clearable>
              <el-option label="未读" value="0" />
              <el-option label="已读" value="1" />
              <el-option label="已批准" value="2" />
              <el-option label="已拒绝" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="notificationList">
          <el-table-column label="序号" align="center" type="index" width="50" />
          <el-table-column label="参保人" align="center" prop="insuredName" />
          <el-table-column label="身份证号" align="center" prop="idCard" :show-overflow-tooltip="true" />
          <el-table-column label="医疗机构" align="center" prop="hospitalName" />
          <el-table-column label="就诊日期" align="center" prop="visitDate" />
          <el-table-column label="报销金额" align="center" prop="reimbursementAmount" />
          <el-table-column label="通知时间" align="center" prop="notifyTime" />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.status === '0'">未读</el-tag>
              <el-tag type="info" v-else-if="scope.row.status === '1'">已读</el-tag>
              <el-tag type="success" v-else-if="scope.row.status === '2'">已批准</el-tag>
              <el-tag type="warning" v-else-if="scope.row.status === '3'">已拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="success"
                @click="handleMarkRead(scope.row)"
                v-if="scope.row.status === '0'"
              >标记已读</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="handleApprove(scope.row)"
                v-if="scope.row.status === '1'"
              >批准报销</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleReject(scope.row)"
                v-if="scope.row.status === '1'"
              >拒绝报销</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetail(scope.row)"
              >查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
      
      <el-tab-pane label="医保账户" name="account">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>医保局账户信息</span>
          </div>
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="账户编号">{{ accountInfo.medicalInsuranceNumber }}</el-descriptions-item>
            <el-descriptions-item label="账户类型">{{ accountInfo.medicalInsuranceType }}</el-descriptions-item>
            <el-descriptions-item label="当前余额">
              <span style="color: #409EFF; font-weight: bold;">{{ accountInfo.balance.toFixed(2) }} 元</span>
            </el-descriptions-item>
            <el-descriptions-item label="管理部门">{{ accountInfo.administrativeDepartment }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ accountInfo.creatTime }}</el-descriptions-item>
            <el-descriptions-item label="最后更新">{{ accountInfo.updateTime }}</el-descriptions-item>
          </el-descriptions>

          <div style="margin-top: 20px;">
            <el-table v-loading="loadingTrans" :data="transactionList" style="width: 100%" stripe>
              <el-table-column label="交易时间" align="center" prop="transactionTime" />
              <el-table-column label="交易类型" align="center" prop="transactionType">
                <template slot-scope="scope">
                  <el-tag type="danger" v-if="scope.row.transactionType === 0">支出</el-tag>
                  <el-tag type="success" v-else-if="scope.row.transactionType === 1">收入</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="交易金额" align="center" prop="amount" />
              <el-table-column label="交易对象" align="center" prop="targetName" :show-overflow-tooltip="true" />
              <el-table-column label="交易说明" align="center" prop="description" :show-overflow-tooltip="true" />
            </el-table>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 详情对话框 -->
    <el-dialog title="报销详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="参保人">{{ detail.insuredName }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detail.idCard }}</el-descriptions-item>
        <el-descriptions-item label="医疗机构">{{ detail.hospitalName }}</el-descriptions-item>
        <el-descriptions-item label="就诊日期">{{ detail.visitDate }}</el-descriptions-item>
        <el-descriptions-item label="门诊/住院">{{ detail.visitType === '1' ? '门诊' : '住院' }}</el-descriptions-item>
        <el-descriptions-item label="医疗总费用">{{ detail.totalAmount }} 元</el-descriptions-item>
        <el-descriptions-item label="自付金额">{{ detail.selfPayAmount }} 元</el-descriptions-item>
        <el-descriptions-item label="报销金额">{{ detail.reimbursementAmount }} 元</el-descriptions-item>
        <el-descriptions-item label="报销比例" :span="2">{{ detail.reimbursementRatio }} %</el-descriptions-item>
        <el-descriptions-item label="诊断信息" :span="2">{{ detail.diagnosis }}</el-descriptions-item>
        <el-descriptions-item label="通知时间" :span="2">{{ detail.notifyTime }}</el-descriptions-item>
        <el-descriptions-item label="通知状态" :span="2">
          <el-tag type="danger" v-if="detail.status === '0'">未读</el-tag>
          <el-tag type="info" v-else-if="detail.status === '1'">已读</el-tag>
          <el-tag type="success" v-else-if="detail.status === '2'">已批准</el-tag>
          <el-tag type="warning" v-else-if="detail.status === '3'">已拒绝</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getInsuranceBureauList, getAccountDetail, getTransactionRecord, changeStatus} from "@/api/medical/insurancebureau";
export default {
  name: "InsuranceBureau",
  data() {
    return {
      // 当前激活的选项卡
      activeTab: 'notification',
      // 遮罩层
      loading: false,
      loadingTrans: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知列表
      notificationList: [],
      // 账户信息
      accountInfo: {
        medicalInsuranceNumber: '',
        medicalInsuranceType: '',
        balance: 0,
        administrativeDepartment: '',
        creatTime: '',
        updateTime: ''
      },
      // 交易记录
      transactionList: [],
      // 详情对话框
      detailOpen: false,
      // 详情数据
      detail: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        insuredName: undefined,
        status: undefined
      }
    };
  },
  created() {
    this.getList();
    this.fetchTransactionRecord();
    this.fetchAccountDetail()
  },
  methods: {
    /** 查询通知列表 */
    async getList() {
      this.loading = true;
      try {
        const res = await getInsuranceBureauList();
        // 转换数据格式
        this.notificationList = (res.rows || []).map(item => ({
          id: item.id,
          insuredName: item.insuredPersons?.name,
          idCard: item.identificationCard,
          hospitalName: item.medicalInstitution,
          visitDate: item.visitTime,
          reimbursementAmount: item.reimbursementAmount?.toFixed(2),
          notifyTime: item.notificationTime,
          status: item.status?.toString(),
          totalAmount: item.payMoney?.toFixed(2),
          selfPayAmount: (item.payMoney - item.reimbursementAmount)?.toFixed(2),
          reimbursementRatio: ((item.reimbursementAmount / item.payMoney) * 100)?.toFixed(0),
          visitType: '1', // 默认为门诊
          diagnosis: '暂无诊断信息' // 如果后端没有提供诊断信息，则显示默认值
        }));
        this.total = this.notificationList.length;
      } catch (error) {
        this.$message.error('获取报销通知列表失败：' + error.message);
      } finally {
        this.loading = false;
      }
    },
    /** 查询交易记录 */
    async fetchTransactionRecord() {
      this.loadingTrans = true;
      const res = await getTransactionRecord();
      this.transactionList = res.rows.map(item => {
        return {
          transactionTime: item.createTime,
          transactionType: item.type,
          amount: item.money,
          targetName: item.userId,
          description: item.remark 
        }
      })
      this.loadingTrans = false;
    },
    // 查询医保局财务处账户信息
    async fetchAccountDetail() {
      this.loadingTrans = true;
      try {
        const res = await getAccountDetail();
        if (res.code === 200 && res.data) {
          this.accountInfo = {
            medicalInsuranceNumber: res.data.medicalInsuranceNumber,
            medicalInsuranceType: res.data.medicalInsuranceType,
            balance: res.data.balance,
            administrativeDepartment: res.data.administrativeDepartment,
            creatTime: res.data.creatTime,
            updateTime: res.data.updateTime
          };
          // 更新交易记录
          if (res.data.transactionRecords) {
            this.transactionList = res.data.transactionRecords.map(item => ({
              transactionTime: item.createTime,
              transactionType: item.type,
              amount: item.money.toFixed(2),
              targetName: item.insuredPersons?.name || item.userId,
              description: item.remark
            }));
          }
        }
      } catch (error) {
        this.$message.error('获取账户信息失败：' + error.message);
      } finally {
        this.loadingTrans = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      this.detail = row;
      this.detailOpen = true;
    },
    /** 标记已读按钮操作 */
    async handleMarkRead(row) {
      this.loading = true;
      await changeStatus({
        id: row.id,
        status: 1
      })
      this.loading = false;
      this.getList()
    },
    /** 批准报销按钮操作 */
    handleApprove(row) {
      this.$confirm('确认批准 ' + row.insuredName + ' 的报销申请吗?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }).then(async () => {
        this.loading = true;
        await changeStatus({
          id: row.id,
          status: 2
        })
        this.$message({
          type: "success",
          message: "报销已批准，通知将发送给医保基金开户银行"
        });
        this.loading = false;
        this.getList()
      }).catch(() => {});
    },
    /** 拒绝报销按钮操作 */
    handleReject(row) {
      this.$confirm('确认拒绝 ' + row.insuredName + ' 的报销申请吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        this.loading = true;
        await changeStatus({
          id: row.id,
          status: 3
        })
        this.$message({
          type: "success",
          message: "报销已拒绝"
        });
        this.loading = false;
        this.getList()
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style> 